import routes from "./routes";
import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";

Vue.use(VueRouter);

const oldPushMethod = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, onComplate = () => {}, onAbort = () => {}) {
    return oldPushMethod.call(this, location, onComplate, onAbort);
};

const oldReplaceMethod = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, onComplate = () => {}, onAbort = () => {}) {
    return oldReplaceMethod.call(this, location, onComplate, onAbort);
};

const router = new VueRouter({
    routes,
    mode: "history",
});

const whitePath = ["login", "home", "register", "search", "detail", "addCartSuccess"];

router.beforeEach(async (to, from, next) => {
    const token = store.state.user.token;
    if (token) {
        if (to.name === "login") {
            next("/home");
        } else {
            // 判断是否存在userInfo
            const isUserInfo = !!store.state.user.userInfo.nickName;
            if (isUserInfo) {
                next();
            } else {
                try {
                    await store.dispatch("user/getUserInfo");
                    next();
                } catch (error) {
                    store.dispatch("user/getResetUser"); //重置user中的所有信息
                    next(`/login?redirect=${to.name}`);
                }
            }
        }
    } else {
        if (whitePath.includes(to.name)) {
            next();
        } else {
            next(`/login?redirect=${to.name}`);
        }
    }
});

export default router;
